<template>
  <div class="pet-home-container">
    <!-- 轮播图部分 -->
    <div class="carousel-section">
      <el-carousel :interval="4000" type="card" height="320px">
        <el-carousel-item v-for="item in carouselItems" :key="item.bannerId">
          <div class="carousel-content">
            <el-image
              :src="item.imageUrl"
              fit="cover"
              style="width: 100%; height: 100%"
            />
            <div class="carousel-caption">
              <h3>{{ item.title }}</h3>
              <p>{{ item.remark || "轮播图" }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 宠物列表部分 -->
    <div class="pets-section">
      <div class="section-header">
        <h2 class="section-title">宠物列表</h2>
        <el-link type="primary" @click="navigateToList">查看全部</el-link>
      </div>
      <div class="pet-card-list">
        <el-row :gutter="20">
          <el-col
            v-for="pet in petList"
            :key="pet.recipeId"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card
              class="pet-card"
              shadow="hover"
              @click="navigateToPet(pet.recipeId)"
            >
              <div class="pet-image">
                <el-image
                  :src="pet.coverImage || ''"
                  fit="cover"
                  style="width: 100%; height: 200px"
                ></el-image>
                <div class="pet-status">
                  <el-tag
                    :type="
                      pet.status === '1'
                        ? 'warning'
                        : pet.status === '2'
                        ? 'info'
                        : 'success'
                    "
                  >
                    {{
                      pet.status === "1"
                        ? "待领养"
                        : pet.status === "2"
                        ? "已确定领养"
                        : "已领养"
                    }}
                  </el-tag>
                </div>
              </div>
              <div class="pet-info">
                <h3 class="pet-name">{{ pet.recipeName }}</h3>
                <p class="pet-category">
                  分类:
                  {{ pet.categoryName || getCategoryName(pet.categoryId) }}
                </p>
                <div class="pet-meta">
                  <span>{{ pet.age }}岁</span>
                  <span>{{
                    pet.gender === 1 ? "公" : pet.gender === 2 ? "母" : "未知"
                  }}</span>
                </div>
                <p class="pet-description">{{ pet.description }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { listBanner } from "@/api/banner";
import { treeCategory } from "@/api/category";
import { listRecipe } from "@/api/recipe";
import { ElMessage } from "element-plus";

const router = useRouter();
const categoryOptions = ref([]);
const petList = ref([]);
const carouselItems = ref([]);

// 获取轮播图数据
const getBannerData = () => {
  // 调用轮播图API
  listBanner({
    status: "0", // 只获取状态为正常的轮播图
    pageSize: 100, // 限制获取数量
  })
    .then((res) => {
      if (res.code === 200 && res.rows) {
        // 添加后端 host 地址
        carouselItems.value = (res.rows || []).map((item) => ({
          ...item,
          imageUrl: `http://127.0.0.1:8080${item.imageUrl}`,
        }));
      }
    })
    .catch((error) => {
      console.error("获取轮播图数据失败:", error);
      // 即使出错也不使用模拟数据，因为接口一定会返回数据
    });
};

// 获取分类数据
const getCategoryData = () => {
  // 调用分类API获取分类树
  treeCategory()
    .then((res) => {
      if (res.code === 200 && res.data) {
        categoryOptions.value = res.data;
      } else {
        // 接口调用失败，使用默认数据
        useMockCategoryData();
      }
    })
    .catch(() => {
      // 出错时使用默认数据
      useMockCategoryData();
    });
};

// 使用模拟分类数据
const useMockCategoryData = () => {
  categoryOptions.value = [
    {
      categoryId: 1,
      categoryName: "猫咪",
      children: [
        { categoryId: 4, categoryName: "英短" },
        { categoryId: 5, categoryName: "加菲" },
        { categoryId: 6, categoryName: "暹罗" },
      ],
    },
    {
      categoryId: 2,
      categoryName: "狗狗",
      children: [
        { categoryId: 7, categoryName: "金毛" },
        { categoryId: 8, categoryName: "哈士奇" },
        { categoryId: 9, categoryName: "泰迪" },
      ],
    },
    {
      categoryId: 3,
      categoryName: "其他宠物",
      children: [
        { categoryId: 10, categoryName: "兔子" },
        { categoryId: 11, categoryName: "仓鼠" },
      ],
    },
  ];
};

// 获取宠物列表
const getPetList = () => {
  // 调用宠物API获取列表
  listRecipe({
    pageNum: 1,
    pageSize: 8,
    orderByColumn: "create_time",
    isAsc: "desc",
    status: "1", // 首页优先展示待领养的宠物
  })
    .then((res) => {
      if (res.code === 200 && res.rows) {
        if (res.rows.length > 0) {
          petList.value = res.rows;
        } else {
          // 如果没有待领养的宠物，则获取全部宠物
          return listRecipe({
            pageNum: 1,
            pageSize: 8,
            orderByColumn: "create_time",
            isAsc: "desc",
          });
        }
      } else {
        throw new Error(res.msg || "获取宠物列表失败");
      }
    })
    .then((res) => {
      // 处理第二次请求结果
      if (res && res.code === 200 && res.rows) {
        petList.value = res.rows;
      }
    })
    .catch((error) => {
      // 出错时使用默认数据
      console.error("获取宠物列表失败:", error);
      ElMessage.warning("获取宠物列表失败，显示模拟数据");
      useMockPetData();
    });
};

// 使用模拟宠物数据
const useMockPetData = () => {
  const mockData = [];
  for (let i = 0; i < 8; i++) {
    mockData.push({
      recipeId: i + 1,
      recipeName: "可爱的" + (i % 2 === 0 ? "小猫" : "小狗") + (i + 1),
      categoryId: i % 3 === 0 ? 1 : i % 3 === 1 ? 2 : 3,
      coverImage:
        i % 2 === 0
          ? "https://img0.baidu.com/it/u=1394778073,2898249422&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333"
          : "https://img1.baidu.com/it/u=1970091545,917553451&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333",
      age: Math.floor(Math.random() * 10) + 1,
      gender: i % 2 === 0 ? 1 : 2,
      status: i % 3 === 0 ? "1" : i % 3 === 1 ? "2" : "3",
      description:
        "这是一只非常可爱的" +
        (i % 2 === 0 ? "小猫" : "小狗") +
        "，它非常友好，适合家庭饲养。",
    });
  }
  petList.value = mockData;
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  // 使用递归函数在分类树中查找指定ID的分类
  function findCategory(categories, id) {
    for (const category of categories) {
      if (category.categoryId == id) {
        return category;
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children, id);
        if (found) return found;
      }
    }
    return null;
  }

  const category = findCategory(categoryOptions.value, categoryId);
  return category ? category.categoryName : categoryId;
};

// 导航到宠物详情页
const navigateToPet = (petId) => {
  router.push(`/pet/detail/${petId}`);
};

// 导航到宠物列表页
const navigateToList = () => {
  router.push("/pet/list");
};

onMounted(() => {
  getBannerData();
  getCategoryData();
  getPetList();
});
</script>

<style scoped>
.pet-home-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.section-title {
  position: relative;
  font-size: 24px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  color: #303133;
}

.section-title::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #409eff;
}

.carousel-section {
  margin-bottom: 40px;
}

.carousel-content {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 15px;
}

.carousel-caption h3 {
  margin: 0 0 10px 0;
  font-size: 22px;
  font-weight: bold;
}

.carousel-caption p {
  margin: 0;
  font-size: 14px;
}

.pets-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pet-card-list {
  margin-bottom: 20px;
}

.pet-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.pet-image {
  position: relative;
  height: 180px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.pet-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.pet-info {
  padding: 15px 0;
}

.pet-name {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.pet-category {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.pet-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.pet-description {
  margin: 0;
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

@media (max-width: 768px) {
  .carousel-section {
    margin-bottom: 20px;
  }

  .pets-section {
    margin-bottom: 20px;
  }
}
</style>
